﻿#region 命名空间

using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.Unity.InterceptionExtension;


#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 验证处理类
    /// </summary>
    public class ValidationHandler : ICallHandler
    {
        /// <summary>
        /// 验证类型名称
        /// </summary>
        public Type Type { get; set; }

        /// <summary>
        /// 换行符
        /// </summary>
        public static string NewLine { get; set; }


        public int Order { get; set; }

        public ValidationHandler(Type type, int order)
        {
            Type = type;
            Order = order;
        }

        /// <summary>
        /// 构造函数，此处不可省略，否则会导致异常
        /// </summary>
        /// <param name="attributes">配置文件中所配置的参数</param>
        public ValidationHandler(NameValueCollection attributes)
        {
            Order = Convert.ToInt32(attributes["Order"]);
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            ValidationResults results = ValidationFactory.CreateValidator(Type).Validate(input.Target);
            if (!results.IsValid)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var result in results)
                {
                    sb.Append("关键字 = " + result.Key + NewLine);
                    sb.Append("消息 = " +
                              result.Message + NewLine + result.Message + NewLine);
                }

                throw new InvalidOperationException(sb.ToString());
            }

            return getNext()(input, getNext);
        }
    }
}